#include "CIOSSwitchBtn.h"
#include <QTimer>
#include <QPainter>


void CIOSSwitchBtn::OnBeginAnimation()
{
	int i = 0.05 * m_heightSize;
	int n = m_widthSize - 0.95 * m_heightSize;
	if (m_ios)
	{
		m_currentValue += 1;
		if (m_currentValue > n - 1)
			m_timer->stop();
	}
	else
	{
		m_currentValue -= 1;
		if (m_currentValue < i)
			m_timer->stop();
	}
	update();
}

CIOSSwitchBtn::CIOSSwitchBtn(QWidget *parent, int ctlWidth, int ctlHeight)
	: QWidget(parent)
{
	ui.setupUi(this);
	setMaximumSize(ctlWidth, ctlHeight);
	setMinimumSize(ctlWidth, ctlHeight);
	m_widthSize = (float)this->width();
	m_heightSize = (float)this->height();
	m_timer = new QTimer(this);
	m_timer->setInterval(50);
// 	if (m_ios)
// 		m_currentValue = m_widthSize - 0.95 * m_heightSize;
// 	else

	m_currentValue = m_heightSize * 0.05;
	connect(m_timer, SIGNAL(timeout()), SLOT(OnBeginAnimation()));

}

CIOSSwitchBtn::~CIOSSwitchBtn()
{
}

void CIOSSwitchBtn::WriteSwitchBttonState(bool ios)
{
	m_ios = ios;
	update();
}

bool CIOSSwitchBtn::ReadSwitchButtonState()
{
	return m_ios;
}

void CIOSSwitchBtn::paintEvent(QPaintEvent* event)
{
	Q_UNUSED(event);
	QPainter _painter(this);
	_painter.setRenderHint(QPainter::SmoothPixmapTransform);
	_painter.setRenderHint(QPainter::Antialiasing);
	_painter.setPen(Qt::NoPen);
	if (m_ios)
	{
		_painter.save();
		_painter.setBrush(Qt::green);
		QRectF greenRect = QRectF(0,0,m_widthSize,m_heightSize);
		_painter.drawRoundedRect(greenRect, 0.5 * m_heightSize, 0.5 * m_widthSize);
		_painter.restore();

		_painter.save();
		_painter.setBrush(Qt::white);
		m_currentValue = m_widthSize - 0.95 * m_heightSize;
		_painter.drawEllipse(m_currentValue, 0.05 * m_heightSize, 0.9 * m_heightSize, 0.9 * m_heightSize);
		_painter.restore();
	}
	else
	{
		_painter.save();
		QColor grayColor(199, 199, 199);
		_painter.setBrush(grayColor);
		QRectF roundRect = QRectF(0,0,m_widthSize,m_heightSize);
		_painter.drawRoundedRect(roundRect, 0.5 * m_heightSize, 0.5 * m_heightSize);
		_painter.restore();
#if 0
		_painter.save();
		_painter.setBrush(Qt::red);
		QRectF redRect = QRectF(0, 0, m_widthSize, m_heightSize);
		_painter.drawRoundedRect(redRect, 0.45 * m_heightSize, 0.45 * m_heightSize);
		_painter.restore();
#endif

		_painter.save();
		_painter.setBrush(Qt::white);
		_painter.drawEllipse(m_currentValue, 0.05 * m_heightSize, 0.9 * m_heightSize, 0.9 * m_heightSize);
		_painter.restore();
	}
}

void CIOSSwitchBtn::mousePressEvent(QMouseEvent* event)
{
	Q_UNUSED(event);
	m_ios = !m_ios;
	m_timer->start(10);
	emit sig_stateChange();
	update();
}
